package com.example.confirm3.service;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * ClassName:MessageService
 * Package:com.example.ttl1.service
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/8/11-21:30
 * @Version:v1.0
 */
@Service
@Slf4j
public class MessageService{

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${my.exchangeName}")
    private String exchangeName;


    @PostConstruct //构造方法后执行,相当于初始化作用
    public void init() {
        rabbitTemplate.setConfirmCallback(
                //匿名内部类
                new RabbitTemplate.ConfirmCallback() {
                    @Override
                    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                        log.info("关联id为:{}", correlationData.getId());
                        if (ack) {
                            log.info("消息正确的到达交换机");
                            return;
                        }

                        //ack 为 false 说明没有到达交换机
                        log.error("消息没有到达交换机,原因为:{}", cause);
                    }
                }
        );
    }

    public void sendMsg() {

        Message message = MessageBuilder.withBody("过期时间TTL".getBytes()).build();

        CorrelationData correlationData = new CorrelationData();
        correlationData.setId("order_123456");

        rabbitTemplate.convertAndSend(exchangeName, "info", message, correlationData);

        log.info("消息发送完毕,发送时间为:{}", new Date());
    }


}
